#include <string.h>  
#include <stdio.h>  
#include <assert.h>  
#include <math.h>  
#include "dominion.h"  
#include "dominion_helpers.h"  
#include "rngs.h" 

void randomTestAdventurer( struct gameState *pre, int handPos, int p ) {
  int r, choice1, choice2, choice3, cardDrawn;
  int currentPlayer = whoseTurn(pre);
  int z = 0;
  int temphand[MAX_HAND];
  int drawntreasure = 0;
  struct gameState post;

  memcpy(&post, pre, sizeof(struct gameState));
  SelectStream(2);
  PutSeed(3);  
  
  choice1 = floor(Random()*256);
  choice2 = floor(Random()*256);
  choice3 = floor(Random()*256);
  //printf("test3\n");			/*****************************/
  r = cardEffect(adventurer, choice1, choice2, choice3, &post, handPos, 0);
  assert( r == 0 );
  //printf("test2\n");		/*****************************/
  while(drawntreasure<2){
		if (pre->deckCount[currentPlayer] <1)		//if the deck is empty we need to shuffle discard and add to deck
			shuffle(currentPlayer, pre);
		drawCard(currentPlayer, pre);
		cardDrawn = pre->hand[currentPlayer][pre->handCount[currentPlayer]-1];//top card of hand is most recently drawn card.
		if (cardDrawn == copper || cardDrawn == gold)		// adjusted for introduced bug in dominion.c code from previous assignment
			drawntreasure++;
		else{
			temphand[z]=cardDrawn;
			pre->handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one).
			z++;
		}
     }
   while(z-1>=0){
		pre->discard[currentPlayer][pre->discardCount[currentPlayer]++]=temphand[z-1]; // discard all cards in play that have been drawn
		z=z-1;
   }


  printf("Checking game state... ");
  assert( memcmp(&post, pre, sizeof(struct gameState)) == 0 ); 
  printf("PASSED!\n");
}  

int main() {
  int i, k, j, n, handPos, p, numPlayers;

  struct gameState g;

  PutSeed(3);
  SelectStream(2);

  for(n=0; n<2000; n++) {
    for(i=0; i<sizeof(struct gameState); i++) 
      ((char *)&g)[i] = floor(Random()*256);
    
    numPlayers = floor(Random()*MAX_PLAYERS);
    p = floor(Random()*numPlayers);

    g.deckCount[p] = floor(Random()*MAX_DECK);
    g.discardCount[p] = floor(Random()*MAX_DECK);
    g.handCount[p] = floor(Random()*MAX_HAND);
	g.whoseTurn = p;
	for(k=0; k<g.playedCardCount; k++)
		g.playedCards[k] = floor(Random()*MAX_DECK);
	for(j=0; j < MAX_DECK; j++) {
		g.deck[p][j] = floor(Random() * 25 );
		g.hand[p][j] = floor(Random() * 25 );
		g.discard[p][j] = floor(Random() * 25 );
	}
    g.numActions = 0;
    g.whoseTurn = p;
    g.numPlayers = numPlayers;
    handPos = floor(Random()*g.handCount[p]);    

    randomTestAdventurer( &g, handPos, p );
  }

  printf("All tests PASSED!\n");
  
  return 0;

}